package org.pook.address;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.pook.address.persistance.HibernateUtil;

public class JpaTemplate implements org.pook.address.handler.JpaHandler{

	private static Logger logger = Logger.getLogger(JpaTemplate.class);

	@Override
	public <T> T findById(Class<T> clazz, long id) {
		T o = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		try{
			o = (T)session.load(clazz, id);
		}catch (Exception e) {
			logger.error(e.getMessage());
		}
		return o;
	}

	@Override
	public <T> List<T> findByNameQuery(String name) {		
		Session session = HibernateUtil.getSessionFactory().openSession();
		List<T> l = null;
		try{
			Query q = session.getNamedQuery(name);
			l = (List<T>)q.list();
		}catch (Exception e) {
			logger.error(e.getMessage());
		}
		return l;
	}

	@Override
	public <T> Long insert(T o) {
		Transaction tx = null;		
		Long id = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		try{
			tx = session.beginTransaction();
			id = (Long) session.save(o);						
			tx.commit();			
		}catch (RuntimeException e) {			
			tx.rollback();
			logger.error("rollback ", e);
		}
		return id;
	}

	@Override
	public <T> boolean update(T o) {
		Transaction tx = null;		
		boolean flag = false;
		Session session = HibernateUtil.getSessionFactory().openSession();
		try{
			tx = session.beginTransaction();
			session.update(o);			
			tx.commit();	
			flag = true;
		}catch (RuntimeException e) {			
			tx.rollback();
			logger.error("rollback ", e);
		}
		return flag;
	}

	@Override
	public <T> boolean delete(T o) {
		Transaction tx = null;		
		boolean flag = false;
		Session session = HibernateUtil.getSessionFactory().openSession();
		try{
			tx = session.beginTransaction();
			session.delete(o);
			tx.commit();	
			flag = true;
		}catch (RuntimeException e) {			
			tx.rollback();
			logger.error("rollback ", e);
		}
		return flag;
	}

	@Override
	public <T> boolean deleteById(Class<T> clazz, long id) {
		T o = this.findById(clazz,id);
		return delete(o);
	}

	@Override
	public <T> void evict(T o) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.evict(o);		
	}
 
}